package it.koutifaris.travianmap.dal.sqlservices.travianserver;

import static it.koutifaris.testforclassutils.IsTestForAssert.assertIsTestFor;
import it.koutifaris.travianmap.dal.TravianServerService.TravianServer;
import it.koutifaris.travianmap.dal.TravianServerSettingsService.TravianServerSettings;
import it.koutifaris.travianmap.dal.sqlservices.AbstractServerServiceTest;
import junit.framework.Assert;

public class SqlTravianServerSettingsServiceTest extends AbstractServerServiceTest {

	private SqlTravianServerSettingsService settingsService;

	@Override
	protected void overridableSetUp() {
		settingsService = new SqlTravianServerSettingsService(getDbHelper().getWritableDatabase());
	}

	public void testPkgAndName() {
		assertIsTestFor(SqlTravianServerSettingsService.class);
	}

	public void testGetSettginsForOnEmptyDb() {
		TravianServerSettings serverSettings = settingsService.getSettginsFor(TEST_SERVER);
		Assert.assertNull(serverSettings);
	}

	public void testSaveSettings() {
		TravianServerSettings settings = writeSettings();
		TravianServerSettings savedSettings = settingsService.getSettginsFor(TEST_SERVER);

		Assert.assertEquals(settings, savedSettings);
	}

	public void testWriteOnServerTable() {
		TravianServerSettings settings = writeSettings();

		SqlTravianServerService sqlTravianServerService = new SqlTravianServerService(getDbHelper().getWritableDatabase());
		TravianServer server = sqlTravianServerService.getServer(TEST_SERVER);

		Assert.assertEquals(settings.getServer(), server.getServerId());
	}

	public void testUpdateSetting() {
		TravianServerSettings settings = writeSettings();
		TravianServerSettings updatedSettings = updateSettings();

		TravianServerSettings savedSettings = settingsService.getSettginsFor(TEST_SERVER);
		Assert.assertTrue(updatedSettings.equals(savedSettings));
		Assert.assertFalse(settings.equals(savedSettings));
	}

	private TravianServerSettings writeSettings() {
		TravianServerSettings settings = TravianServerSettingsBuilder.settingsBuilder()
				.setServer(TEST_SERVER)
				.setAutoUpdate(true)
				.setWifiOnly(false)
				.build();

		settingsService.saveSettings(settings);

		return settings;
	}

	private TravianServerSettings updateSettings() {
		TravianServerSettings settings = TravianServerSettingsBuilder.settingsBuilder()
				.setServer(TEST_SERVER)
				.setAutoUpdate(false)
				.setWifiOnly(true)
				.build();

		settingsService.saveSettings(settings);

		return settings;
	}
}
